package com.kkb.controller;

import com.github.pagehelper.PageInfo;
import com.kkb.pojo.Menu;
import com.kkb.pojo.User;
import com.kkb.service.ResourceService;
import com.kkb.vo.ResultVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Lxy
 * @create 2022-03-22 0:57
 */

@Controller
@RequestMapping("resource")
public class ResourceController {

    @Resource
    private ResourceService resourceService;

    //只有管理员才有资源管理的权限才会进来
    @RequestMapping(value = "menuList",method = RequestMethod.GET)
    @ResponseBody
    public ResultVo<Menu> getMenuList(int pageNum,String ResourceName){
        PageInfo<Menu> pageInfo = resourceService.getMenuList(pageNum, 3,ResourceName);
        return new ResultVo<>(pageInfo);
    }

    //资源编辑页初始化
    @RequestMapping(value = "/edit/{m_id}",method = RequestMethod.GET)
    private ModelAndView ResEditInit(@PathVariable("m_id") int m_id,HttpServletRequest request){
        HttpSession session = request.getSession();
        Menu menu = resourceService.getMenuById(m_id);
        session.setAttribute("menu",menu);
        ModelAndView mv = new ModelAndView();
        //mv.setViewName("Resource/edit");
        mv.setViewName("redirect:/welcome/Resource/edit.jsp");
        return mv;
    }

    //资源编辑页的更新操作
    @RequestMapping(value = "{m_id}",method = RequestMethod.PUT)
    @ResponseBody
    public ResultVo updateResEdit(@PathVariable("m_id") int id,Menu menu){
        int validateMenuName = resourceService.validateMenuName(id, menu);
        int validateState = resourceService.validateState(id, menu);
        //修改后存在同名菜单资源
        if (validateMenuName == -1){
            return new ResultVo(500,"存在重复的菜单名字!");
        }
        //没有任何修改
        if (validateMenuName == 0 && validateState == 0){
            return new ResultVo(200,"未进行任何修改!");
        }
        //菜单名字合法修改 或者 菜单状态有修改
        if (validateMenuName == 1 || (validateMenuName == 0 && validateState == 1)){
            menu.setM_id(id);
            int i = resourceService.updateMenu(menu);
            if (i > 0){
                return new ResultVo(200,"更新成功！");
            }
        }
        return new ResultVo(500,"服务器错误，更新失败！");
    }

}
